package com.yt.server;

import com.yt.server.api.IGlobalScope;
import com.yt.server.api.IScope;
import com.yt.server.api.IScopeResolver;
import com.yt.server.exception.ScopeException;

public class ScopeResolver implements IScopeResolver {

	public static final String DEFAULT_HOST = "";

	protected IGlobalScope globalScope;

	public IGlobalScope getGlobalScope() {
		return globalScope;
	}

	public void setGlobalScope(IGlobalScope root) {
		this.globalScope = root;
	}

	public IScope resolveScope(String path) {
		return resolveScope(globalScope, path);
	}

	public IScope resolveScope(IScope root, String path) {
		IScope scope = root;
		if (path != null || !"".equals(path)) {
			final String[] parts = path.split("/");
			for (String room : parts) {
				if (room == null || "".equals(room)) {
					continue;
				}
				if (scope.hasChildScope(room)) {
					scope = scope.getScope(room);
				} else if (!scope.equals(root)) {
					if (scope.createChildScope(room,null, null, false)) {
						scope = scope.getScope(room);
					}
				}
				if (scope == root) {
					throw new ScopeException(room + "not found");
				}
			}
		}
		return scope;
	}
}
